<template>
  <div class="login" v-loading="loading">
    <div class="login_container">
      <div class="login_form">
        <p style="font-size: 30px;font-weight: bold; margin: 56px 0 40px;">账号登录</p>
        <Form
          style="width: 100%;height: 70%"
          ref="login_form"
          hide-required-mark :model="formValidate"
          :rules="ruleValidate" :label-width="50"
          label-position="left">
          <FormItem label="账号" prop="account">
            <Input size="large" style="width: 100%;height: 50px" v-model="formValidate.account"
                   placeholder="请输入账号"></Input>
          </FormItem>
          <FormItem label="密码" prop="password">
            <Input size="large" style="width: 100%;height: 50px" type="password" v-model="formValidate.password"
                   placeholder="请输入密码"></Input>
          </FormItem>
          <p style="margin-bottom: 20px">已阅读并同意《xx协议》</p>
          <Button size="large" style="width: 100%;" type="primary" @click="login">Submit</Button>
        </Form>
      </div>
      <div class="qr_code_box">
        <p style="font-size: 30px;font-weight: bold;width: 100%;text-align: center; margin: 56px 0 40px;"
           @click="$router.push({query: {}})">简书路径</p>
        <div class="qr_code_square"></div>
<!--        <div id="qr_code" class="qr_code"></div>-->
        <div class="qr_code">
          <img class="img" ref="img" :src="imgSrc" alt="">
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import "@/untils/wx";
import { httpRequest } from "@/untils/httpRequest";

// // 获取当前页面的code
// function GetQueryString(name) {
//   var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
//   var r = window.location.search.substr(1).match(reg);
//   if (r != null) return unescape(r[2]);
//   return null;
// }

export default {
  name: "login",
  data() {
    return {
      formValidate: {
        account: "",
        password: ""
      },
      ruleValidate: {
        account: [
          { required: true, message: "账号不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ]
      },
      randomNum: 0,
      loading: false,
      imgSrc: require('@/assets/logo.png')
    };
  },
  methods: {
    login() {
      this.$refs["login_form"].validate((valid) => {
        if (valid) {
          const params = {
            account: this.formValidate.account,
            password: this.formValidate.password
          };
          this.loading = true;
          httpRequest("POST", "/user/login", null, params, "proxy").then(res => {
            if (res.data.code === 200) {
              localStorage.setItem("menu_list", JSON.stringify(res.data.data.menu_list));
              localStorage.setItem("user", JSON.stringify(res.data.data.user));
              this.$router.push("/");
              this.$message.success(res.data.msg);
            }
            this.loading = false;
          });
        }
      });
    },
    // 获取二维码
    getWxQrCode() {
      let flgRandomNum = Math.random();
      this.randomNum = String(flgRandomNum);
      localStorage.setItem("randomNum", String(flgRandomNum));
      new WxLogin({
        self_redirect: false,  //值为true时，直接在二维码的弹窗中进行页面跳转及其余操作,
        id: "qr_code",       //需要承载二维码的容器id
        appid: "wx55dbf016c113a65c",
        scope: "snsapi_login",     //网页授权，目前网页只有这一种方式，静默授权
        redirect_uri: encodeURIComponent(`${document.location.protocol}//clercloud.com/cmc/#/login`),     //回调域名(地址前部分是项目域名，后部分loginSuccess是微信需要跳转的路径（vue中的路由名称）)
        state: flgRandomNum,
        style: "black",
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDI2MHB4O30KLmltcG93ZXJCb3ggLnRpdGxlIHtkaXNwbGF5OiBub25lO30KaWZyYW1le2JvcmRlcjogMXB4IHNvbGlkIHJlZDt9"
      });
    }
  },

  watch: {
    $route: {
      immediate: true,
      deep: true,
      handler() {
        // 获取code state
        var code = this.$route.query.code;
        var state = this.$route.query.state;
        var localState = localStorage.getItem("randomNum");
        if (code && state) {
          if (state === localState) {
            // this.$router.push('/')
            this.$message.success("登录成功");
          } else {
            this.$message.error("state不一致,请重新扫描二维码");
            this.$router.push({ query: {} }); // 清空地址栏参数
            this.getWxQrCode();
          }
        }
      }
    }
  },
  mounted() {
    this.getWxQrCode();
  }
};
</script>

<style lang="less">
.login {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url("/public/img/bg.jpg") no-repeat;
  background-size: cover;

  .login_container {
    width: 700px;
    height: 500px;
    border-radius: 4px;
    box-shadow: 0 0 10px gray;
    padding: 0 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .login_form {
      width: 300px;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .qr_code_box {
      width: 300px;
      height: 100%;
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;

      .qr_code_square {
        width: 260px;
        height: 260px;
        position: absolute;
        top: 130px;
        z-index: 9999;
      }

      .qr_code {
        width: 300px;
        height: 350px;
        position: absolute;
        top: 115px;
        .img {
          width: 100%;
        }
      }
    }
  }
}
</style>